﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using vHCS.HR.Business;
using vHCS.HR.Entities;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using System.Data;
using Core.Common.Session;
using System.Configuration;
using K2CoreLib;
using System.Collections.Specialized;
using vHCS.K2App.Shared;

#region K2 process

#endregion

namespace vHCS.K2App.MdlK2.Termination.Ver1
{
    public partial class TER_AppForResignation : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region CONST

        protected const string _CMD_LAWDATE = "LawDate";

        #endregion
        # region Global
        private string EmpId = string.Empty;
        private long contractType = 0;
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ////lblError.Text = "ID = " + K2CoreLib.K2Utils.GetTypeIDProcessFromEfrom("HR_TerminationRequest");
                    ////lblError.Text = "ID = " + K2CoreLib.K2Utils.GetTypeIDProcessFromEfrom()
                    dpkNow.SelectedDate = DateTime.Now;
                    TER_AppForResignationCollection collection = new TER_AppForResignationCollection();
                    TER_AppForResignationDTO dto = new TER_AppForResignationDTO();

                    this.EmpHeaderInFo.LoadEmpInfo(SessionManager.UserDomain);
                    DataTable dat = new DataTable();

                    dat = collection.LoadEmpInfo(SessionManager.UserDomain);

                    EmpId = dat.Rows[0]["EmployeeId"].ToString().Trim();
                    hdfEmpId.Value = dat.Rows[0]["EmployeeId"].ToString().Trim();
                    hdfHierarchyId.Value = dat.Rows[0]["HierarchyId"].ToString().Trim();

                    TER_DecideLeaveWorkCollection clDWL = new TER_DecideLeaveWorkCollection();
                    TER_DecideLeaveWorkDTO dtoDLW = new TER_DecideLeaveWorkDTO();
                    dtoDLW = clDWL.SelectEmpID(Convert.ToInt64(EmpId));
                    if (dtoDLW != null)
                    {
                        BusinessLogicCustomException ex = new BusinessLogicCustomException("10187");
                        ex.AdditionInfo = new String[] { dtoDLW.EmpCode };
                        throw ex;
                    }
                    else
                    {
                        dto = collection.SelectById(Convert.ToInt64(EmpId));
                        contractType = this.LoadEmpInfo(EmpId);
                        
                        if (dto != null)
                        {
                            LoadEmpForUpdate(dto);
                            //Kiểm tra nếu không phải mẫu tin trả về thì ẩn nút submit
                            string SN = Request.QueryString["sn"] == null ? "" : Request.QueryString["sn"].ToString();
                            try
                            {
                                string sharedUser = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : string.Empty;
                                hdfEmpId.Value = K2CoreLib.K2Utils.GetDataField(SN, "EmpID", sharedUser);
                            }
                            catch
                            {
                                btnTopSubmit.Enabled = false;
                                btnBottomSubmit.Enabled = false;
                            }
                        }
                        else
                        {
                            this.txtRequestDate.SelectedDate = DateTime.Now;
                            this.txtLasDateForLaw.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                            this.txtLastDateMyDream.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                        }
                        ClientScript.RegisterStartupScript(Page.GetType(), "LoadMaximize", "LoadMaximize();", true);
                    }

                    //Gán radtooltip
                    rttNgaylamdon.TargetControlID = txtRequestDate.ClientID + "_dateInput_wrapper";
                    rttLastDateMyDream.TargetControlID = txtLastDateMyDream.ClientID + "_dateInput_wrapper";
                    rttLasDateForLaw.TargetControlID = txtLasDateForLaw.ClientID + "_dateInput_wrapper";
                    rttLastDateApprove.TargetControlID=txtLastDateApprove.ClientID+"_dateInput_wrapper";
                    //
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }

        }
        /// <summary>
        /// load thông tin nhân viên xin thôi việc 
        /// </summary>
        /// <param name="dto"></param>thông tin TER_AppForResignationDTO
        protected void LoadEmpForUpdate(TER_AppForResignationDTO dto)
        {
            if (dto.RequireDate.Year > 1)
            {
                this.txtRequestDate.SelectedDate = dto.RequireDate;
            }
            else
            {
                this.txtRequestDate.SelectedDate = null;
            }

            this.txtLastDateMyDream.SelectedDate = dto.AspirateDate;
            this.txtLasDateForLaw.SelectedDate = dto.LawDate;
            if (dto.ApproveDate.Year > 1)
            {
                this.txtLastDateApprove.SelectedDate = dto.ApproveDate;
            }
            else
            {
                this.txtLastDateApprove.SelectedDate = null;
            }
            this.txtTerminalReason.Text = dto.LeaveWorkReason;
        }
        /// <summary>
        /// Laod thông tin người cho thôi việc
        /// </summary>
        /// <param name="EmpId"></param>id của nhân viên
        /// <returns></returns>
        protected long LoadEmpInfo(string EmpId)
        {
            try
            {
                TER_DecideLeaveWorkCollection collection = new TER_DecideLeaveWorkCollection();
                HR_EmpHeaderInfoDTO dto = new HR_EmpHeaderInfoDTO();
                dto = collection.LoadEmpInfo(Convert.ToInt64(EmpId));
                if (dto != null)
                {
                    this.txtRequester.Text = dto.FullName;
                    this.txtOrgChart.Text = dto.OrgChart;
                    this.txtLocation.Text = dto.WorkingOffice;
                    this.txtStartDate.Text = dto.JoinDate.ToShortDateString();
                    this.txtEmpCode.Text = dto.EmpCode;
                    this.txtSignDate.Text = dto.EffectiveDate.ToShortDateString();
                    this.txtJobTitle.Text = dto.JobTitle;
                    hdfJobLevel.Value = dto.JobLevel;
                    hdfReportingLine.Value = dto.ReportTo;

                    this.txtContractType.Text = dto.ContractName;

                    return dto.LSContractTypeID;
                }
                else
                {
                    this.txtRequester.Text = "";
                    this.txtOrgChart.Text = "";
                    this.txtLocation.Text = "";
                    this.txtStartDate.Text = "";
                    this.txtEmpCode.Text = "";
                    this.txtSignDate.Text = "";
                    this.txtJobTitle.Text = "";
                    this.txtContractType.Text = "";
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return -1;
        }
        /// <summary>
        /// Xử lý sự kiện khi nhấn nút  submit(lưu thông tin nv xin thôi việc)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnTopSubmit_Click(object sender, EventArgs e)
        {
            this.AddNewInfo();
        }
        /// <summary>
        /// Xử lý sự kiện khi nhấn nút  submit(lưu thông tin nv xin thôi việc)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBottomSubmit_Click(object sender, EventArgs e)
        {
            this.AddNewInfo();

        }

        /// <summary>
        /// Thêm mới,update thông tin xin thôi việc
        /// Tanldt thêm process K2
        /// </summary>
        protected void AddNewInfo()
        {
            try
            {
                //kiểm tra nhân viên đã được công ty cho nghỉ thì không được làm đơn xin thôi việc
                TER_DecideLeaveWorkCollection clDWL = new TER_DecideLeaveWorkCollection();
                TER_DecideLeaveWorkDTO dtoDLW = new TER_DecideLeaveWorkDTO();
                vHCS.SYS.Business.SYS_MailTemplateCollection cl_mail = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                dtoDLW = clDWL.SelectEmpID(Convert.ToInt64(hdfEmpId.Value.Trim()));
                if (dtoDLW != null)
                {
                    this.SetEmpty();
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("10187");
                    ex.AdditionInfo = new String[] { dtoDLW.EmpCode };
                    throw ex;
                }
                TER_AppForResignationBL dto = new TER_AppForResignationBL();
                TER_AppForResignationCollection collection = new TER_AppForResignationCollection();
                dto.EmpID = Convert.ToInt64(hdfEmpId.Value.Trim());
                dto.RequireDate = Convert.ToDateTime(txtRequestDate.SelectedDate);
                dto.AspirateDate = Convert.ToDateTime(txtLastDateMyDream.SelectedDate);
                dto.ApproveDate = Convert.ToDateTime(txtLastDateApprove.SelectedDate);
                dto.LawDate = Convert.ToDateTime(txtLasDateForLaw.SelectedDate);
                dto.LeaveWorkReason = System.Text.RegularExpressions.Regex.Replace(this.txtTerminalReason.Text.Trim(), "<[^>]*>", string.Empty);
                TER_AppForResignationDTO bo = new TER_AppForResignationDTO();
                bo = collection.SelectById(Convert.ToInt64(hdfEmpId.Value.Trim()));
                //kiểm tra ngày làm đơn > ngày vào công ty
                TER_DecideLeaveWorkCollection clEmp = new TER_DecideLeaveWorkCollection();
                HR_EmpHeaderInfoDTO dtoEmp = new HR_EmpHeaderInfoDTO();
                if (this.txtRequestDate.SelectedDate != null)
                {

                    dtoEmp = clEmp.LoadEmpInfo(Convert.ToInt64(hdfEmpId.Value));
                    if (txtRequestDate.SelectedDate <= dtoEmp.JoinDate)
                    {
                        BusinessLogicCustomException ex = new BusinessLogicCustomException("10195");
                        ex.AdditionInfo = new String[] { dtoEmp.JoinDate.ToShortDateString() };
                        throw ex;

                    }
                }

                //kiểm tra ngày làm theo nguyện vọng >= ngày làm hiệu lực cuối cùng trong quá trình làm việc
                if (this.txtLastDateMyDream.SelectedDate < dtoEmp.WorkingEffectiveDate)
                {
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("10196");
                    ex.AdditionInfo = new String[] { dtoEmp.WorkingEffectiveDate.ToShortDateString() };
                    throw ex;
                }
                if (bo != null)
                {
                    //Cập nhật thông tin xin thôi việc
                    collection.Update(dto);

                    string sn = Request.QueryString["SN"] == null ? "" : Request.QueryString["SN"].ToString();
                    if (!string.IsNullOrEmpty(sn))
                    {
                        K2CoreLib.K2Utils.ActionExecute(sn, "Submit", null);
                    }

                    //Insert history
                    HR_WorkingRecordCollection cl_his = new HR_WorkingRecordCollection();
                    cl_his.InsertHistory(bo.LeaveWorkID, DateTime.Now, SessionManager.UserDomain, "Requester", "Submitted", "", 2,0);

                    MessageBox.ShowByMessCode("10010");

                    btnBottomSubmit.Enabled = false;
                    btnTopSubmit.Enabled = false;
                }
                else
                {
                    //Thêm mới thông tin xin thôi việc
                    Int64 LeaveWorkID = collection.AddNew(dto);
                    string version = ConfigurationManager.AppSettings.Get("TER_CurrentVersion");

                    try
                    {
                        K2Collection colK2 = new K2Collection();
                        string CB = ConfigurationManager.AppSettings.Get("Termination_CB");
                        //Active Process K2
                        string sEmpID = this.hdfEmpId.Value.ToString();
                        HIE_EmpInHierarchyCollection cl_emphie = new HIE_EmpInHierarchyCollection();
                        string sHierID = cl_emphie.SelectDeptHie(Convert.ToInt64(string.IsNullOrEmpty(hdfHierarchyId.Value.ToString()) ? "0" : hdfHierarchyId.Value.ToString())).ToString();
                        string HRPBLead = colK2.GetUserOfHRPLeader(EmpHeaderInFo.EmployeeId);
                        string DeptHead = colK2.GetLeaderOfHierarchy(Convert.ToInt64(string.IsNullOrEmpty(sHierID) ? "0" : sHierID));
                        string HR = colK2.GetUserOfHR();
                        string NextApproved = colK2.GetReportingLine(EmpHeaderInFo.EmployeeId);
                        List<string> listUserCC = new List<string>();

                        if (NextApproved != "")
                        {
                            listUserCC.Add(HRPBLead);
                            listUserCC.Add(DeptHead);
                            listUserCC.Add(CB);
                            listUserCC.Add(HR);
                            string ApproveLink = ConfigurationManager.AppSettings.Get("LinkTerminationApprove");

                            #region Lấy nội dung mail để gửi next approve
                            HR_WorkingRecordBL bl_wr=new HR_WorkingRecordBL();
                            HR_WorkingRecordCollection cl_wr=new HR_WorkingRecordCollection();
                            HIE_HierarchyBL bl_hie=new HIE_HierarchyBL();
                            HIE_HierarchyCollection cl_hie=new HIE_HierarchyCollection();
                            bl_wr=cl_wr.SelectLastWRByEmpID(EmpHeaderInFo.EmployeeId);
                            string contentmail = ReturnMailContent("Termination_NextApprove");
                            contentmail = contentmail.Replace("$Creator$", SessionManager.UserDomain);
                            contentmail = contentmail.Replace("$url$", ApproveLink);
                            string subjectmail = ReturnSubjectMail("Termination_NextApprove");
                            subjectmail = subjectmail.Replace("$Creator$", SessionManager.UserDomain);
                            subjectmail = subjectmail.Replace("$Account$",EmpHeaderInFo.Username);
                            //Lấy Hierarchycode của node depthead
                            long hie_dept = cl_emphie.SelectDeptHie(bl_wr.HierarchyId);//Lấy node depthead
                            bl_hie=cl_hie.SelectByID(hie_dept);
                            //
                            subjectmail = subjectmail.Replace("$Dept$",bl_hie.HierarchyCode);
                            string emailapprove = ReturnEmail(NextApproved);
                            string emailhr = ReturnEmail(HR);
                            #endregion

                            #region Lấy nội dung để gửi mail requester
                            String strBuilder = "";
                            strBuilder = ConfigurationManager.AppSettings.Get("LinkTerminationRequest");
                            strBuilder += "?ID=" + LeaveWorkID.ToString() + "&User=" + EmpHeaderInFo.Username;
                            strBuilder = HttpUtility.HtmlEncode(strBuilder);

                            string MailContent_Request = ReturnMailContent("Termination_Request");
                            MailContent_Request = MailContent_Request.Replace("$RequestDate$", DateTime.Now.ToShortDateString());
                            MailContent_Request = MailContent_Request.Replace("$Approver$", NextApproved);
                            //Convert string to Url
                            MailContent_Request = MailContent_Request.Replace("$url$", strBuilder.ToString());

                            string MailSubject_Request = ReturnSubjectMail("Termination_Request");
                            string EmailRequester = ReturnEmail(EmpHeaderInFo.Username);
                            #endregion

                            #region Lấy nội dung mail gửi HR,DH,HRP,Executor khi Creator submitted
                            string UserName = EmpHeaderInFo.Username;
                            string FullName = txtRequester.Text;
                            string EmpCode = txtEmpCode.Text;

                            //Lấy thông tin bộ phân, phòng ban
                            long DivisionID = cl_emphie.SelectDivHie(Convert.ToInt64(hdfHierarchyId.Value.Trim()));
                            long DeptID = cl_emphie.SelectDeptHie(Convert.ToInt64(hdfHierarchyId.Value.Trim()));
                            string Division = "";
                            string Dept = "";
                            //Gán bộ phận
                            bl_hie = cl_hie.SelectByID(DivisionID);
                            if (bl_hie.DTO != null)
                                Division = bl_hie.HierarchyCode;
                            //Gán phòng ban
                            bl_hie = cl_hie.SelectByID(DeptID);
                            if (bl_hie.DTO != null)
                                Dept = bl_hie.HierarchyCode;

                            string JobTitle = txtJobTitle.Text;
                            string JobLevel = hdfJobLevel.Value;
                            string ReportingLine = hdfReportingLine.Value;
                            string ExitReason = txtTerminalReason.Text.Trim();
                            string LastWorkingDate = Convert.ToDateTime(txtLastDateMyDream.SelectedDate).ToShortDateString();
                            //

                            //Gán các thông tin thôi việc vào nội dung mail
                            string MailContent_HR = ReturnMailContent("Termination_CreatorToHR");

                            MailContent_HR = MailContent_HR.Replace("$EmpCode$", EmpCode);
                            MailContent_HR = MailContent_HR.Replace("$FullName$", FullName);
                            MailContent_HR = MailContent_HR.Replace("$Account$", EmpHeaderInFo.Username);
                            MailContent_HR = MailContent_HR.Replace("$Div/Dep$", Division + "/" + Dept);
                            MailContent_HR = MailContent_HR.Replace("$JobTitle$", JobTitle);
                            MailContent_HR = MailContent_HR.Replace("$JobLevel$", JobLevel);
                            MailContent_HR = MailContent_HR.Replace("$ReportingLine$", ReportingLine);
                            MailContent_HR = MailContent_HR.Replace("$ExitReason$", ExitReason);
                            MailContent_HR = MailContent_HR.Replace("$LastWorkingDate$", LastWorkingDate);
                            MailContent_HR = MailContent_HR.Replace("$url$", strBuilder.ToString());
                            MailContent_HR = MailContent_HR.Replace("$CreatedBy$", SessionManager.UserDomain);
                            //

                            //Gán các thông tin thôi việc vào subject mail
                            string MailSubject_HR = ReturnSubjectMail("Termination_CreatorToHR");
                            MailSubject_HR = MailSubject_HR.Replace("$Dept$", Dept);
                            MailSubject_HR = MailSubject_HR.Replace("$Account$", EmpHeaderInFo.Username);
                            MailSubject_HR = MailSubject_HR.Replace("$Creator$",SessionManager.UserDomain);
                            //

                            //Lấy địa chỉ mail DeptHead,HRP,CB
                            String MailDeptHead = ReturnEmail(DeptHead);
                            String MailHRP = ReturnEmail(colK2.GetUserOfHRP(EmpHeaderInFo.EmployeeId));
                            String MailCB = ReturnEmail(CB);

                            #endregion

                            int iTypeID = K2CoreLib.K2Utils.GetTypeIDProcessFromEfrom("HR_TerminationRequest");
                            string sLinkContent = ConfigurationManager.AppSettings.Get("History_TER") + LeaveWorkID.ToString() + "&User=" + EmpHeaderInFo.Username;
                            string status = "0"; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                            string eformid = K2CoreLib.K2Utils.submit2EForm(SessionManager.UserDomain, SessionManager.UserDomain, iTypeID, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), sLinkContent, status,EmpHeaderInFo.Username);
                            string[] lst_eformid = eformid.Split(',');

                            //Get current version
                            string currentversion = ConfigurationManager.AppSettings.Get("TER_CurrentVersion");
                            string ViewHistoryLink = strBuilder.ToString();
                            //Get expire day
                            string ExpireDay = ConfigurationManager.AppSettings.Get("TER_ExpireDay");
                            string ExpireAlert = ConfigurationManager.AppSettings.Get("TER_ExpireAlert");
                      
                            int proid = K2CoreLib.K2Utils.StartTerProcess(sEmpID, sHierID, NextApproved, SessionManager.UserDomain, LeaveWorkID.ToString(), contentmail, subjectmail, emailapprove,
                                                                           MailSubject_Request, MailContent_Request, EmailRequester, MailSubject_HR,
                                                                           MailContent_HR, MailDeptHead, MailHRP, MailCB, emailhr, lst_eformid[1], lst_eformid[0], cl_mail.ReturnEmail(HRPBLead), currentversion,EmpHeaderInFo.Username
                                                                           ,ApproveLink,ViewHistoryLink,ExpireDay,ExpireAlert);
                            K2CoreLib.K2Utils.Update2EForm("0", lst_eformid[1], proid.ToString());
                            collection.UpdateEform(LeaveWorkID, lst_eformid[1]);
                            //lblError.Text = processIn.ToString();
                            MessageBox.ShowByMessCode("10044");
                            this.btnTopSubmit.Enabled = false;
                            this.btnBottomSubmit.Enabled = false;
                        }
                        else
                            lblError.Text = "Chưa có gắng user trên Node";
                        //End Process

                        //Insert history
                        HR_WorkingRecordCollection cl_his = new HR_WorkingRecordCollection();
                        cl_his.InsertHistory(LeaveWorkID, DateTime.Now, SessionManager.UserDomain, "Requester", "Submitted", "", 2, 0);

                        //Insert CC (Reviewer) comment
                        HistoryComment his = new HistoryComment();
                        his.InsertReviewerComment(LeaveWorkID, listUserCC, 2);

                        //MessageBox.ShowByMessCode("10044");
                        ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                    }
                    catch (Exception ex)
                    {
                        collection.Delete(LeaveWorkID);
                        throw ex;
                    }
                }

            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }

        /// <summary>
        /// Trả về nội cung mail cần gửi trong K2 theo mail code truyền vào
        /// </summary>
        /// <param name="Creator"></param>
        /// <returns></returns>
        public string ReturnMailContent(string MailCode)
        {
            try
            {
                vHCS.SYS.Business.SYS_MailTemplateBL bl = new vHCS.SYS.Business.SYS_MailTemplateBL();
                vHCS.SYS.Business.SYS_MailTemplateBL bl_signature = new vHCS.SYS.Business.SYS_MailTemplateBL();
                vHCS.SYS.Business.SYS_MailTemplateCollection cl = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                bl = cl.FindByCode(MailCode);
                //Lấy nội dung signature gán vào nội dung mail
                bl_signature = cl.FindByCode("K2-Signature");

                if (bl.DTO != null)
                {
                    string content = bl.ContentVN;
                    content += bl_signature.ContentVN;
                    return content;
                }
                
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return "";
        }

        /// <summary>
        /// Trả về nội subject mail theo mail code truyền vào
        /// </summary>
        /// <param name="MailCode"></param>
        /// <returns></returns>
        public string ReturnSubjectMail(string MailCode)
        {
            try
            {
                vHCS.SYS.Business.SYS_MailTemplateBL bl = new vHCS.SYS.Business.SYS_MailTemplateBL();
                vHCS.SYS.Business.SYS_MailTemplateCollection cl = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                bl = cl.FindByCode(MailCode);
                if (bl.DTO != null)
                {
                    string title = bl.TitleVN;
                    return title;
                }

            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return "";
        }

        /// <summary>
        /// Lấy địa chỉ mail theo username
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public string ReturnEmail(string UserName)
        {
            try
            {
                vHCS.SYS.Business.SYS_UsersBL bl_user = new vHCS.SYS.Business.SYS_UsersBL();
                vHCS.SYS.Business.SYS_UsersCollection cl_user = new vHCS.SYS.Business.SYS_UsersCollection();
                bl_user = cl_user.FindById_BL(UserName);
                if (bl_user.DTO != null)
                    return bl_user.Email;
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
            return "";
        }

        protected void ajxManager_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            try
            {
                if (e.Argument.Equals(_CMD_LAWDATE))
                {
                    TER_AppForResignationCollection collection = new TER_AppForResignationCollection();
                    this.txtLasDateForLaw.SelectedDate = collection.GenerateLawDate(Convert.ToDateTime(this.txtRequestDate.SelectedDate), contractType);
                    this.txtLastDateMyDream.SelectedDate = collection.GenerateLawDate(Convert.ToDateTime(this.txtRequestDate.SelectedDate), contractType);
                    this.txtLastDateMyDream.DataBind();
                    this.txtLasDateForLaw.DataBind();
                }

            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }

        }
        /// <summary>
        /// Refresh lại giao diện ban đầu
        /// </summary>
        protected void SetEmpty()
        {
            try
            {
                txtRequestDate.SelectedDate = null;
                txtLastDateMyDream.SelectedDate = null;
                txtLasDateForLaw.SelectedDate = null;
                txtLastDateApprove.SelectedDate = null;
                txtTerminalReason.Text = null;
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }

        }

        protected void HR_ctrEmpHeader_OnUserChanged(object sender, EventArgs e)
        {
            try
            {
                TER_AppForResignationCollection collection = new TER_AppForResignationCollection();
                TER_AppForResignationDTO dto = new TER_AppForResignationDTO();

                DataTable dat = new DataTable();

                dat = collection.LoadEmpInfo(EmpHeaderInFo.Username);

                EmpId = dat.Rows[0]["EmployeeId"].ToString().Trim();
                hdfEmpId.Value = dat.Rows[0]["EmployeeId"].ToString().Trim();
                hdfHierarchyId.Value = dat.Rows[0]["HierarchyId"].ToString().Trim();

                TER_DecideLeaveWorkCollection clDWL = new TER_DecideLeaveWorkCollection();
                TER_DecideLeaveWorkDTO dtoDLW = new TER_DecideLeaveWorkDTO();
                dtoDLW = clDWL.SelectEmpID(Convert.ToInt64(EmpId));
                if (dtoDLW != null)
                {
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("10187");
                    ex.AdditionInfo = new String[] { dtoDLW.EmpCode };
                    throw ex;
                }
                else
                {
                    dto = collection.SelectById(Convert.ToInt64(EmpId));
                    contractType = this.LoadEmpInfo(EmpId);

                    if (dto != null)
                    {
                        LoadEmpForUpdate(dto);
                        //Kiểm tra nếu không phải mẫu tin trả về thì ẩn nút submit
                        string SN = Request.QueryString["sn"] == null ? "" : Request.QueryString["sn"].ToString();
                        string sharedUser = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : string.Empty;
                        try
                        {
                            if(!string.IsNullOrEmpty(SN))
                                
                                hdfEmpId.Value = K2CoreLib.K2Utils.GetDataField(SN, "EmpID", sharedUser);
                        }
                        catch
                        {
                            btnTopSubmit.Enabled = false;
                            btnBottomSubmit.Enabled = false;
                        }
                    }
                    else
                    {
                        this.txtRequestDate.SelectedDate = DateTime.Now;
                        this.txtLasDateForLaw.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                        this.txtLastDateMyDream.SelectedDate = collection.GenerateLawDate(DateTime.Now, contractType);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
    }
}